import pandas as pd
import numpy as np
from datetime import datetime, timedelta
import random

def generate_customer_data(n_customers=1000):
    """生成模拟用户数据"""
    customer_ids = range(1, n_customers + 1)
    genders = ['Male', 'Female']
    ages = np.random.normal(35, 10, n_customers).astype(int)
    ages = np.clip(ages, 18, 70)
    
    data = {
        'customer_id': customer_ids,
        'gender': [random.choice(genders) for _ in customer_ids],
        'age': ages,
        'membership_days': np.random.randint(30, 1000, n_customers),
        'avg_monthly_spend': np.random.gamma(5, 20, n_customers),
        'product_category': [random.choice(['Electronics', 'Clothing', 'Food', 'Books', 'Home']) for _ in customer_ids]
    }
    
    return pd.DataFrame(data)

def generate_purchase_history(customers_df, max_purchases_per_customer=20):
    """为每个用户生成购买历史"""
    all_purchases = []
    
    for _, customer in customers_df.iterrows():
        n_purchases = random.randint(1, max_purchases_per_customer)
        customer_id = customer['customer_id']
        
        # 首次购买日期在会员开始后的随机时间
        first_purchase_date = datetime.now() - timedelta(days=random.randint(1, customer['membership_days']))
        
        for i in range(n_purchases):
            # 计算本次购买距离首次购买的天数
            days_since_first = random.randint(0, customer['membership_days'] - 1)
            purchase_date = first_purchase_date + timedelta(days=days_since_first)
            
            # 购买金额与用户平均消费相关
            amount = max(5, np.random.normal(customer['avg_monthly_spend']/30 * (i+1), 20))
            
            # 计算是否为复购（基于一些因素的函数）
            is_repurchase = calculate_repurchase_likelihood(customer, days_since_first, i)
            
            all_purchases.append({
                'customer_id': customer_id,
                'purchase_date': purchase_date,
                'amount': round(amount, 2),
                'is_repurchase': is_repurchase,
                'product_category': customer['product_category']
            })
    
    return pd.DataFrame(all_purchases)

def calculate_repurchase_likelihood(customer, days_since_first, purchase_number):
    """计算用户进行复购的概率"""
    # 基础概率
    base_probability = 0.3
    
    # 会员时长影响：会员时间越长，复购可能性越高
    membership_factor = min(1.0, customer['membership_days'] / 365 * 0.5)
    
    # 购买次数影响：购买次数越多，越可能复购
    purchase_factor = min(1.0, purchase_number / 5 * 0.4)
    
    # 平均消费影响：消费越高，越可能复购
    spend_factor = min(1.0, customer['avg_monthly_spend'] / 500 * 0.3)
    
    # 时间间隔影响：首次购买后时间越长，越可能复购
    time_factor = min(1.0, days_since_first / 180 * 0.3)
    
    # 产品类别影响
    category_factors = {
        'Electronics': 0.2,
        'Clothing': 0.5,
        'Food': 0.8,
        'Books': 0.4,
        'Home': 0.3
    }
    category_factor = category_factors[customer['product_category']]
    
    # 计算最终概率
    final_probability = base_probability + membership_factor + purchase_factor + spend_factor + time_factor + category_factor
    final_probability = min(1.0, final_probability)
    
    return random.random() < final_probability

def generate_and_save_data():
    """生成数据并保存到CSV文件"""
    customers = generate_customer_data(1000)
    purchases = generate_purchase_history(customers)
    
    customers.to_csv('customer_data.csv', index=False)
    purchases.to_csv('purchase_history.csv', index=False)
    
    print("数据生成完成并保存到CSV文件")
    return customers, purchases

if __name__ == "__main__":
    customers, purchases = generate_and_save_data()    